import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export interface User {
  id: number
  username: string
  email: string
}

export const useAuthStore = defineStore('auth', () => {
  const user = ref<User | null>(null)
  const isLoggedIn = computed(() => !!user.value)

  const mockUsers = [
    { id: 1, username: 'admin', password: 'admin123', email: 'admin@example.com' },
    { id: 2, username: 'user', password: '123456', email: 'user@example.com' }
  ]

  const login = async (username: string, password: string): Promise<boolean> => {
    await new Promise(resolve => setTimeout(resolve, 500))

    const foundUser = mockUsers.find(u => u.username === username && u.password === password)
    if (foundUser) {
      user.value = {
        id: foundUser.id,
        username: foundUser.username,
        email: foundUser.email
      }
      localStorage.setItem('user', JSON.stringify(user.value))
      return true
    }
    return false
  }

  const logout = () => {
    user.value = null
    localStorage.removeItem('user')
  }

  const initializeAuth = () => {
    const savedUser = localStorage.getItem('user')
    if (savedUser) {
      try {
        user.value = JSON.parse(savedUser)
      } catch (error) {
        console.error('Error parsing user from localStorage', error)
      }
    }
  }

  return {
    user,
    isLoggedIn,
    login,
    logout,
    initializeAuth
  }
})
